/**
 * 开店模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	//图片翻页
	function picRoll() {
		 var li_num=$(".ldh-intoStore-list li").length;
		 var num=6;//显示数量
		 var ul_width=li_num*148;
		 var one_width=148*num;
		 var ul_left=0;
		 $(".ldh-intoStore-list").css("width",one_width+"px");;
		 if(li_num>num){
			 $(".storebtn-left").css("display","block");
			 $(".storebtn-right").css("display","block");
			 $(".ldh-intoStore-list ul").css("width",ul_width+"px");
			 var max_left=ul_width-one_width;
			 $(".storebtn-left").click(function(){
				 if(ul_left<0){
					 ul_left=ul_left+one_width;
				     $(".ldh-intoStore-list ul").animate({left:ul_left},500);	 
					 }
			 });  
			 $(".storebtn-right").click(function(){
				 if(ul_left>-max_left){
					 ul_left=ul_left-one_width;
				     $(".ldh-intoStore-list ul").animate({left:ul_left},500);	
					 }
				 
			 });
		 }else{
			 $(".storebtn-left").css("display","none");
			 $(".storebtn-right").css("display","none"); 
		 };	  
	}
	
	picRoll();
	
	//开店选择分类
	$(document).on("click",".ldh-storeType-listR div span",function(){
		$(".ldh-storeType-listR div span").removeClass("over");
		$(this).addClass("over");
		$(this).parents(".ldh-storeType-listR").parent().addClass("on").siblings("li").removeClass("on");	
	})
	
	$(document).on("click",".btn-group .btn",function(){
		if(!$(this).parent().hasClass("open")){$(this).parent().addClass("open");}else{$(this).parent().removeClass("open")}
		$(document).on("click",function(event){
			var _target=$(event.target).parents();
			if(!_target.hasClass("btn-group")){
				  $(".btn-group").removeClass("open");				  
			}else{_target.siblings(".btn-group").removeClass("open");}	
		});
	});
	
	$(document).on("click",".btnFile",function(){
		$(this).siblings("input:file").click();	
	});
	
	var validate = require("../../custom/base/component-validate.js");
	
	require("../../custom/base/component-core.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
	
	var async = require("../../custom/base/component-async.js");
	
	require("../../custom/base/component-md5.js");
		
	var head=require("../../custom/head/module-head.js");
	
	head.init(head);
	
	var upload=require("../../custom/base/component-upload.js");
	
	require("../../custom/base/component-map.js");
	
	var identityImage1="",identityImage2="",identityImage3="",longitude="",latitude="",phone="",certificate1="",certificate2="",certificate3="";

	
	//初始化函数
	exports.init=function(m){
		
		window.$ldh_store=m;
		
		base.setFromPage("openStore");
				
		var userId=$("#session_userid").val();
		
		if(!validate.isNull(userId)){
			
			base.hasLoginShow(userId,$("#session_username").val(),$("#session_iconurl").val());
		}else{
			
			base.loginShow();
		}
		
		exports.showAllShopsTypes();
		
		exports.findAllProvince();
		
		//初始化上传控件
		upload.ldh_upload_store("certificate1","/shop/store","$ldh_store.uploadBusinessLicenseCallBack");
		upload.ldh_upload_store("certificate2","/shop/store","$ldh_store.uploadPermitCallBack");
		upload.ldh_upload_store("certificate3","/shop/store","$ldh_store.uploadHealthCallBack");
		upload.ldh_upload_store("identityImage1","/shop/store","$ldh_store.uploadIdentityImage1CallBack");
		upload.ldh_upload_store("identityImage2","/shop/store","$ldh_store.uploadIdentityImage2CallBack");
		upload.ldh_upload_store("identityImage3","/shop/store","$ldh_store.uploadIdentityImage3CallBack");
		
		
		//初始化百度地图
		var map = new BMap.Map("dituContent");
		
		map.centerAndZoom(new BMap.Point(113.275, 23.117), 11);
		function showInfo(e){
			
			latitude=e.point.lat;
			
			longitude=e.point.lng;
			
			map.clearOverlays();         
			
			var point = new BMap.Point(longitude, latitude);
			
			var marker = new BMap.Marker(point);
			
			map.addOverlay(marker);
			
			$("#tip_map").hide();
			
		}
		map.addEventListener("click", showInfo);
		var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
		var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
		var top_right_navigation = new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); //右上角，仅包含平移和缩放按钮
		map.addControl(top_left_control);        
		map.addControl(top_left_navigation);     
		map.addControl(top_right_navigation); 
		map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
		map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
		exports.setMap(map);
		
		
	};
	
	//设置地图对象
	exports.setMap=function(map){
		
		this.map=map;
		
	};
	
	//获取地图对象
	exports.getMap=function(){
		
		return this.map;
		
	};
	
	//地图根据地址移动
	exports.setDragMap=function(address){
		
	   if(typeof address != "undefined"){
			
			var myGeo = new BMap.Geocoder();
			myGeo.getPoint(address, function(point) {
				if (point) {
					exports.getMap().clearOverlays();      
					var myMarker = new BMap.Marker(point);
					exports.getMap().centerAndZoom(point, 11);
					exports.getMap().addOverlay(myMarker);
					//当地图移动时，获取屏幕中间点的坐标
					var center = map.getCenter();    
					
					longitude=center.lng;
					latitude=center.lat;
					//document.getElementById("input-longitude").value = center.lng;
					//document.getElementById("input-latitude").value = center.lat;
					$("#tip_map").hide();
				}
			}, "全国");
			
		}
	};
	
	
	//查询商家分类
	exports.showAllShopsTypes=function(){
		
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx + "/shopweb/ShopsType/showAllShopsTypes.do", ""));
					var parentHtmlStr="";
					if(data["code"]==1){
						for (var i = 0; i < data["shopTypeList"].length; i++) {
							var classStr="",imgStr="";
							if(data["shopTypeList"][i]["shopTypeId"]=="1"){
								classStr="ldh-class-bg-a";
								imgStr=ctx+"/v1/img/classifly_01.png";
							}else if(data["shopTypeList"][i]["shopTypeId"]=="2"){
								classStr="ldh-class-bg-b";
								imgStr=ctx+"/v1/img/classifly_02.png";
							}else if(data["shopTypeList"][i]["shopTypeId"]=="50"){
								classStr="ldh-class-bg-c";
								imgStr=ctx+"/v1/img/classifly_03.png";
							}else if(data["shopTypeList"][i]["shopTypeId"]=="5"){
								classStr="ldh-class-bg-f";
								imgStr=ctx+"/v1/img/classifly_04.png";
							}else if(data["shopTypeList"][i]["shopTypeId"]=="3"){
								classStr="ldh-class-bg-d";
								imgStr=ctx+"/v1/img/classifly_05.png";
							}else if(data["shopTypeList"][i]["shopTypeId"]=="4"){
								classStr="ldh-class-bg-e";
								imgStr=ctx+"/v1/img/classifly_06.png";
							}
							
							
											parentHtmlStr += '<li>';
										
											parentHtmlStr += '<p class="ldh-class-bg '+classStr+'"></p>';
											parentHtmlStr += '<div class="ldh-storeType-listR">';
											parentHtmlStr += '<h3><img src="'+imgStr+'"/></h3><div>';
											for (var j = 0; j< data["shopTypeList"][i]["childTypeList"].length; j++) {
												parentHtmlStr += '<span onclick=$ldh_store.setShopTypeId("'+data["shopTypeList"][i]["childTypeList"][j]["shopTypeId"]+'")>'
														+ data["shopTypeList"][i]["childTypeList"][j]["shopTypeName"]
														+ '</span>';
											}
											parentHtmlStr += '</div></div>';
											parentHtmlStr += '</li>';
						}
						
						
						
					}
					$("#shopTypeList").html(parentHtmlStr);
					
				}))().start();
		
	};
	
	/**
	 * 页面滚动
	 */
	function scrollPage(id,_height){
		
		var height=0;
		
		if(!validate.isNull(_height)){
			
			height=_height;
		}
		
		var this_y=$(id).offset().top-height;
		
		$("html,body").animate({scrollTop:this_y},500);
		
		
	}
	
	/**
	 * 确认开店
	 */
	exports.openShop=function(obj){
		
		var shopName=$("#shopName").val();
		
		var identityNo=$("#identityNo").val();
		
		var address=$("#address").val();
		
		var mobile=$("#open_store_mobile").val();
		
		var payPassword=$("#payPassword").val();
		
		var range=$("#range").val();
		
		if(validate.isNull(exports.getShopTypeId())){
			
			scrollPage("#tip_shopType",80);
			
			$("#tip_shopType").html("店铺分类必须选择");
			
			return;
		}
		
		if(validate.isNull(shopName) || validate.isLength(shopName,20)){
			
			scrollPage("#tip_shopName",80);
			
			$("#tip_shopName").html("请输入正确的店铺名称");
			
			return;
		}

		if(!validate.isIdentity(identityNo)){
			
			scrollPage("#tip_identityNo",80);
			
			$("#tip_identityNo").html("请输入正确的身份证号码");
			
			return;
		}
		
		if(validate.isNull(identityImage1)){
			scrollPage("#identityImage1",280);
			$("#tip_identityImage1").html("请上传身份证正面照");
			$("#tip_identityImage1").show();
			return;
		}else{
			
		}
		if(validate.isNull(identityImage2)){
			scrollPage("#identityImage2",280);
			$("#tip_identityImage2").html("请上传身份证反面照");
			$("#tip_identityImage2").show();
			return;
		}else{
			
		}
		if(validate.isNull(identityImage3)){
			scrollPage("#identityImage3",280);
			$("#tip_identityImage3").html("请上传手持身份证照");
			$("#tip_identityImage3").show();
			return;
		}else{
		
		}
		
	if(validate.isNull(exports.getProvinceId())){
			scrollPage("#tip_area",80);
			$("#tip_area").html("请选择省份");
			return;
		}else{
			
			
		}
		
		if(validate.isNull(exports.getCityId())){
			scrollPage("#tip_area",80);
			$("#tip_area").html("请选择城市");
			return;
		}else{
			
			
		}
		
		if(validate.isNull(exports.getRegionId())){
			scrollPage("#tip_area",80);
			$("#tip_area").html("请选择区域");
			return;
		}else{
			
			
		}
		
		
		if(validate.isNull(address)){
			scrollPage("#tip_address",80);
			$("#tip_address").html("请输入详细地址");
			return;
		}
		
		if(!validate.isMobile(mobile)){
			scrollPage("#tip_open_store_mobile",80);
			$("#tip_open_store_mobile").html("请输入正确的手机号码");
			return;
		}
		
		
		
		if(validate.isNull(range)){
			scrollPage("#tip_range",80);
			$("#tip_range").html("请输入配送范围");
			return;
		}
		
		
		
		if(!validate.isPayPassword(payPassword)){
			scrollPage("#tip_payPassword",80);
			$("#tip_payPassword").html("该密码必须是6位数字");
			return;
		}

		
		if(validate.isNull(longitude) || validate.isNull(latitude)){
			scrollPage("#tip_map",870);
			$("#tip_map").html("请选择店铺在地图上的位置");
			$("#tip_map").show();
			return;
		}
		
		var params={
			shopName:shopName,
			identityNo:identityNo,
			phone:phone,
			mobile:mobile,
			payPassword:MD5(payPassword),
			provinceId:exports.getProvinceId(),
			cityId:exports.getCityId(),
			regionId:exports.getRegionId(),
			address:address,
			identityImage1:identityImage1,
			identityImage2:identityImage2,
			identityImage3:identityImage3,
			certificate1:certificate1,
			certificate2:certificate2,
			certificate3:certificate3,
			longitude:longitude,
			latitude:latitude,
			shopTypeId:exports.getShopTypeId(),
			range:range
		};
		
		
		$(obj).html("正在提交...");
		
		$(obj).attr("disabled","disabled");
		
		$(obj).css("background-color","#D3D3D3");
		
		eval(Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/Shop/openShop.do", params));

						if(!base.validateLoginStatus(data)){
							base.loginShow();
							$(obj).html("提交审核");
							$(obj).attr("disabled",false);
							$(obj).css("background-color","#ed5d3a");
							return;
						}
					
					
						if(data.code==1){
							
							
							if(data.toPay=="0"){
								
								window.location.href=ctx+"/v1/pages/store/success.jsp";
								
							}
							
						}else{
							
							$("#tip_openShop").html(data.message);
							
							$(obj).html("提交审核");
							
							$(obj).attr("disabled",false);
							
							$(obj).css("background-color","#ed5d3a");
						}
				

				}))().start();
	};
	
	
	/**
	 * 上传营业执照回调函数
	 */
	exports.uploadBusinessLicenseCallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#certificate1_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					certificate1=dataPath;
				}else{
					alert("上传失败!");
				}
			}
		}
	};
	
	/**
	 * 上传许可证回调函数
	 */
	exports.uploadPermitCallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#certificate2_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					certificate2=dataPath;
				}else{
					alert("上传失败!");
				}
			}
		}
	};
	
	/**
	 * 上传健康证回调函数
	 */
	exports.uploadHealthCallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#certificate3_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					certificate3=dataPath;
				}else{
					alert("上传失败!");
					
				}
			}
		}
	};
	
	/**
	 * 上传身份证正面回调函数
	 */
	exports.uploadIdentityImage1CallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#identityImage1_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					identityImage1=dataPath;
					$("#tip_identityImage1").hide();
				}else{
					alert("上传失败!");
				}
			}
		}
	};
	
	/**
	 * 上传身份证反面回调函数
	 */
	exports.uploadIdentityImage2CallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#identityImage2_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					identityImage2=dataPath;
					$("#tip_identityImage2").hide();
				}else{
					alert("上传失败!");
				}
			}
		}
	};
	
	/**
	 * 上传身份证反面回调函数
	 */
	exports.uploadIdentityImage3CallBack=function(dataObj){
		
		var dataPath = "";
		if(dataObj.code == "1"){
			for(var i=0;i<dataObj.files.length;i++){
				if(dataObj.files[i].repCode=="1"){
					dataPath = dataObj.files[i].path;
					$("#identityImage3_img").css("background-image","url("+fileOpenUrl+dataPath+")");
					identityImage3=dataPath;
					$("#tip_identityImage3").hide();
				}else{
					alert("上传失败!");
				}
			}
		}
	};
	
	/**
	 * 查询所有省份
	 */
	exports.findAllProvince=function(){
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findAllProvince.do", ""));
					
					findAllProvinceCallBack(data);

				}))().start();
		
	};
	
	/**
	 * 查询所有省份_回调函数
	 */
	function findAllProvinceCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
			
			htmlStr+='<li><a href=javascript:$ldh_store.setProvinceId("'+data[i].PROVINCE_ID+'","'+data[i].PROVINCE_NAME+'")>'+data[i].PROVINCE_NAME+'</a></li>';
		}
		
		$("#provinceList").html('<li><a href=javascript:$ldh_store.setProvinceId("","请选择")>请选择</a></li>'+htmlStr);
	}
	
	/**
	 * 根据省份查询城市
	 */
	function findCityByProvince(provinceId){
		
		var params={
			provinceId:provinceId
		};
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findCityByProvince.do",params));
					
					findCityByProvinceCallBack(data);

				}))().start();
	}
	
	/**
	 * 根据省份查询城市
	 */
	function findCityByProvinceCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
						
			htmlStr+='<li><a href=javascript:$ldh_store.setCityId("'+data[i].CITY_ID+'","'+data[i].CITY_NAME+'")>'+data[i].CITY_NAME+'</a></li>';
		}
		
		$("#cityList").html('<li><a href=javascript:$ldh_store.setCityId("","请选择")>请选择</a></li>'+htmlStr);
	}
	
	/**
	 * 根据城市查询区域
	 */
	function findRegionByCity(cityId){
		
		var params={
				cityId:cityId
			};
		
		eval(Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx
							+ "/shopweb/SysParam/findRegionByCity.do",params));
					
					findRegionByCityCallBack(data);

				}))().start();
	}
	
	/**
	 * 根据城市查询区域_回调函数
	 */
	function findRegionByCityCallBack(data){
		
		var htmlStr="";
		
		for(var i=0;i<data.length;i++){
			
			htmlStr+='<li><a href=javascript:$ldh_store.setRegionId("'+data[i].REGION_ID+'","'+data[i].REGION_NAME+'")>'+data[i].REGION_NAME+'</a></li>';

		}
		
		$("#regionList").html('<li><a href=javascript:$ldh_store.setRegionId("","请选择")>请选择</a></li>'+htmlStr);
		
	}
	
	exports.setShopTypeId=function(shopTypeId){
		
		$("#tip_shopType").html("");
		
		this.shopTypeId=shopTypeId;
	
	};
	
	exports.getShopTypeId=function(){
		
		return this.shopTypeId==null?"":this.shopTypeId;
	
	};
	
	exports.setAddressId=function(addressId){
		
		this.addressId=addressId;
	
	};
	
	exports.getAddressId=function(){
		
		return this.addressId==null?"":this.addressId;
		
	};
	
	exports.setProvinceId=function(provinceId,provinceName){
		
		this.provinceId=provinceId;
		
		$("#province_name").html(provinceName);
		
		$("#provinceList").parent().removeClass("open");
		
		exports.setCityId("","请选择");
		
		exports.setRegionId("","请选择");
		
		if(provinceId=="")
			return;
		
		findCityByProvince(provinceId);
		
	};
	
	exports.getProvinceId=function(){
		
		return this.provinceId==null?"":this.provinceId;
		
	};
	
	exports.setCityId=function(cityId,cityName){
		
		this.cityId=cityId;
		
		$("#city_name").html(cityName);
		
		$("#cityList").parent().removeClass("open");
		
		exports.setRegionId("","请选择");
		
		if(cityId=="")
			return;
		
		findRegionByCity(cityId);
		
	};
	
	exports.getCityId=function(){
		
		return this.cityId==null?"":this.cityId;
		
	};
	
	
	exports.setRegionId=function(regionId,regionName){
		
		this.regionId=regionId;
		
		$("#region_name").html(regionName);
		
		$("#regionList").parent().removeClass("open");
		
		
		if(regionId=="")
			return;
		
		exports.setDragMap($("#province_name").text()+$("#city_name").text()+$("#region_name").text());

		
	};
	
	exports.getRegionId=function(){
		
		return this.regionId==null?"":this.regionId;
		
	};
	
	
});

